package com.uphone.kingmall.activity;

import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.adapter.ShoppingCartAdapter;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.ShoppingCartBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentUtils;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/23
 *     desc   :
 * </pre>
 */
public class ShoppingCartActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_manage)
    TextView tvManage;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.tv_go)
    TextView tvGo;
    @BindView(R.id.rl_empty)
    RelativeLayout rlEmpty;
    @BindView(R.id.rv_cart)
    RecyclerView rvCart;
    @BindView(R.id.shop_cart_refresh)
    SwipeRefreshLayout shopCartRefresh;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.ivSelectAll)
    CheckBox ivSelectAll;
    @BindView(R.id.ivSelectAll_ll)
    LinearLayout ivSelectAllLl;
    @BindView(R.id.tvCountMoney)
    TextView tvCountMoney;
    @BindView(R.id.ll_price)
    LinearLayout llPrice;
    @BindView(R.id.btnSettle)
    TextView btnSettle;
    @BindView(R.id.rlBottomBar)
    RelativeLayout rlBottomBar;
    private ShoppingCartAdapter shoppingCartAdapter;
    ShoppingCartBean shoppingCartBean = new ShoppingCartBean();
    private boolean isFirst = true;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_fragment_shop_cart;
    }

    @Override
    public void initView() {
        ivBack.setVisibility(View.VISIBLE);
        rl.setMinimumHeight(MyApplication.height);
        shopCartRefresh.setMinimumHeight(MyApplication.height);
        rvCart.setLayoutManager(new LinearLayoutManager(this));
        shoppingCartAdapter = new ShoppingCartAdapter(this);
        rvCart.setAdapter(shoppingCartAdapter);
        initListener();
    }

    @Override
    public void initData() {
        loadData();
    }

    public void loadData() {
        if (TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
            return;
        }
        OkGoUtils.normalRequest(MyUrl.userShopCar, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                ShoppingCartBean bean = GsonUtils.getGson().fromJson(response, ShoppingCartBean.class);
                if (bean.getCode() == 0) {
                    shoppingCartBean = bean;
                    if (bean.getShopCar() == null || bean.getShopCar().size() == 0) {
                        rvCart.setVisibility(View.GONE);
                        rlEmpty.setVisibility(View.VISIBLE);
                    } else {
                        rvCart.setVisibility(View.VISIBLE);
                        rlEmpty.setVisibility(View.GONE);
                        shoppingCartAdapter.setNewData(shoppingCartBean.getShopCar());
                        //第一次进入，加载完数据后，全部选中
                        if (isFirst) {
                            isFirst = false;
                            ivSelectAll.setChecked(true);
                            onViewClicked(ivSelectAll);
                        } else {
                            ivSelectAll.setChecked(false);
                        }
                    }
                    calculationMoney();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_manage, R.id.tv_go, R.id.ivSelectAll, R.id.btnSettle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_manage:
                if (llPrice.getVisibility() == View.VISIBLE) {
                    llPrice.setVisibility(View.GONE);
                    btnSettle.setText("删除");
                    tvManage.setText("完成");
                } else {
                    llPrice.setVisibility(View.VISIBLE);
                    tvManage.setText("管理");
                    calculationMoney();
                }
                break;
            case R.id.tv_go:
                CommonUtil.startIntent(ShoppingCartActivity.this, SearchGoodsListActivity.class);
                break;
            case R.id.ivSelectAll:
                boolean isChecked = ivSelectAll.isChecked();
                shoppingCartBean.setSelect(isChecked);
                for (int i = 0; i < shoppingCartBean.getShopCar().size(); i++) {
                    shoppingCartBean.getShopCar().get(i).setSelect(isChecked);
                    for (int j = 0; j < shoppingCartBean.getShopCar().get(i).getGoods().size(); j++) {
                        shoppingCartBean.getShopCar().get(i).getGoods().get(j).setSelect(isChecked);
                    }
                }
                shoppingCartAdapter.setNewData(shoppingCartBean.getShopCar());
                calculationMoney();
                break;
            case R.id.btnSettle:
                btnSettle();
                break;
        }
    }

    private void initListener() {
        shopCartRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shopCartRefresh.setRefreshing(false);
                    }
                }, 2000);
                loadData();
            }
        });
        shoppingCartAdapter.setOnShopItemClickListener(new ShoppingCartAdapter.OnShopItemClickListener() {
            @Override
            public void itemClick(View v, int position, ShoppingCartBean.ShopCarBean item) {
                // 店铺点击事件
                CommonUtil.startIntent(ShoppingCartActivity.this, ShopDetailActivity.class, item.getShopId());
            }

            @Override
            public void itemSelect(View v, int position, ShoppingCartBean.ShopCarBean item) {
                // 商铺选中
                itemSelectChange(position, item);
                calculationMoney();
            }

            @Override
            public void itemGoodClick(View v, int childPosition, ShoppingCartBean.ShopCarBean.GoodsBean childItem) {
                // 商品点击事件
                CommonUtil.startIntent(ShoppingCartActivity.this, GoodsDetailActivity.class, childItem.getGoodsId());
            }

            @Override
            public void itemGoodSelect(View v, int position, int childPosition, ShoppingCartBean.ShopCarBean item, ShoppingCartBean.ShopCarBean.GoodsBean childItem) {
                // 商品选中
                itemSelectChange(position, item);
                calculationMoney();
            }

            @Override
            public void itemGoodAmount(View v, int position, int childPosition, ShoppingCartBean.ShopCarBean item,
                                       ShoppingCartBean.ShopCarBean.GoodsBean childItem, int amount, int type) {
                shoppingCartBean.getShopCar().set(position, item);
                changeGoodsNumber(position, childPosition, childItem, type, amount);
            }
        });
    }

    private double priceTotal = 0;
    private int goodsNum = 0;

    private void calculationMoney() {
        priceTotal = 0;
        BigDecimal priceTotalDecimal = new BigDecimal(0);
        goodsNum = 0;
        for (int i = 0; i < shoppingCartBean.getShopCar().size(); i++) {
            for (int j = 0; j < shoppingCartBean.getShopCar().get(i).getGoods().size(); j++) {
                ShoppingCartBean.ShopCarBean.GoodsBean goodsBean = shoppingCartBean.getShopCar().get(i).getGoods().get(j);
                if (goodsBean.isSelect()) {
//                    priceTotal += (goodsBean.getGoodsNum() * goodsBean.getGoodsPerFee());
                    priceTotalDecimal = priceTotalDecimal.add(new BigDecimal(goodsBean.getGoodsNum()).multiply(new BigDecimal(goodsBean.getGoodsPerFee())));
                    goodsNum++;
                }
            }
        }
        priceTotal = priceTotalDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvCountMoney.setText("¥" + priceTotal);
        if (llPrice.getVisibility() == View.VISIBLE) {
            btnSettle.setText("结算(" + goodsNum + ")");
        }
    }

    private void changeGoodsNumber(final int position, final int childPosition, final ShoppingCartBean.ShopCarBean.GoodsBean childItem, int type, final int amount) {
        HttpParams params = new HttpParams();
        params.put("shopCarId", childItem.getShopCarId());
        params.put("type", type);
        OkGoUtils.progressRequest(MyUrl.shopCarGoodsNumChange, ShoppingCartActivity.this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    shoppingCartBean.getShopCar().get(position).getGoods().get(childPosition).setGoodsNum(amount);
                }
                shoppingCartAdapter.setNewData(shoppingCartBean.getShopCar());
                if (childItem.isSelect()) {
                    calculationMoney();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void itemSelectChange(int position, ShoppingCartBean.ShopCarBean item) {
        shoppingCartBean.getShopCar().set(position, item);
        if (!item.isSelect() && ivSelectAll.isChecked()) {
            ivSelectAll.setChecked(false);
            shoppingCartBean.setSelect(ivSelectAll.isChecked());
        } else {
            boolean check = true;
            for (int i = 0; i < shoppingCartBean.getShopCar().size(); i++) {
                if (!shoppingCartBean.getShopCar().get(i).isSelect()) {
                    check = false;
                    break;
                }
            }
            shoppingCartBean.setSelect(check);
            ivSelectAll.setChecked(shoppingCartBean.isSelect());
        }
    }

    private void btnSettle() {
        String shopCarId = "";
        if (shoppingCartBean != null && shoppingCartBean.getShopCar() != null && shoppingCartBean.getShopCar().size() > 0) {
            for (int i = 0; i < shoppingCartBean.getShopCar().size(); i++) {
                if (shoppingCartBean.getShopCar().get(i).getGoods() != null && shoppingCartBean.getShopCar().get(i).getGoods().size() > 0) {
                    for (int j = 0; j < shoppingCartBean.getShopCar().get(i).getGoods().size(); j++) {
                        ShoppingCartBean.ShopCarBean.GoodsBean goodsBean = shoppingCartBean.getShopCar().get(i).getGoods().get(j);
                        if (goodsBean.isSelect()) {
                            shopCarId += goodsBean.getShopCarId() + ",";
                        }
                    }
                }
            }
        }
        if (TextUtils.isEmpty(shopCarId)) {
            ToastUtils.showShortToast(ShoppingCartActivity.this, "您还没有选择商品");
            return;
        }
        String str = shopCarId.substring(0, shopCarId.length() - 1);
        HttpParams params = new HttpParams();
        params.put("shopCarIds", str);


        if (btnSettle.getText().toString().contains("结算")) {
            // 结算
            settleCart(params);
        } else {
            // 删除
            deleteCart(params);
        }
    }

    private void settleCart(HttpParams params) {
        OkGoUtils.progressRequest(MyUrl.getShopCarBalancePage, ShoppingCartActivity.this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    IntentUtils.getInstance().with(ShoppingCartActivity.this, SettleActivity.class).putString(ConstansUtils.JSON_STR, response).start();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void deleteCart(HttpParams params) {
        OkGoUtils.progressRequest(MyUrl.userDelShopCar, ShoppingCartActivity.this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    ToastUtils.showShortToast(ShoppingCartActivity.this, "删除成功");
                }
                loadData();
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }
}
